<template>
  <div>
    <div class="content"></div>
    <van-row>
      <van-col span="24" class="title">
        <span style="color: white">浩物安全管理系统</span>
      </van-col>
    </van-row>

    <van-row class="topMargin">
      <van-col span="6">
        <div
          style="height: 50px; width: 50px; margin-top: 20px; margin-left: 20px"
        >
          <img
            :src="company_logo"
            style="width: 100%; height: 100%"
          />
        </div>
      </van-col>
      <van-col span="18">
        <div style="margin-top: 20px; margin-left: 5px">
          <div style="font-size: 16px">{{ currentUser.companyName }}</div>
          <div style="margin-top: 2px; font-size: 14px" class="light_grey_font">
            {{ company_address }}
          </div>
        </div>
      </van-col>
    </van-row>

    <van-row>
      <van-col span="24">
        <van-grid :border="false">
          <van-grid-item @click="redirectSubPage('usageLog')">
            <van-image :src="require('../../assets/images/title_1.png')" />
            <!-- <img style="width:70px;height:70px" src="../../assets/images/title_1.png" /> -->
            <div class="item_font">用车记录</div>
          </van-grid-item>
          <van-grid-item @click="redirectSubPage('reviewViolations')">
            <van-image :src="require('../../assets/images/title_2.png')" />
            <!-- <img style="width:70px;height:70px" src="../../assets/images/title_2.png" /> -->
            <div class="item_font">违规复核</div>
          </van-grid-item>
          <van-grid-item @click="redirectSubPage('usageStandard')">
            <van-image :src="require('../../assets/images/title_3.png')" />
            <!-- <img style="width:70px;height:70px" src="../../assets/images/title_3.png" /> -->
            <div class="item_font">行驶规范</div>
          </van-grid-item>
          <van-grid-item @click="redirectSubPage('carManage')">
            <van-image :src="require('../../assets/images/title_4.png')" />
            <!-- <img style="width:70px;height:70px" src="../../assets/images/title_4.png" /> -->
            <div class="item_font">车辆管理</div>
          </van-grid-item>
        </van-grid>
      </van-col>
    </van-row>

    <van-row>
      <van-col span="24" class="bg_grey_height"></van-col>
    </van-row>
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
    <van-row>
      <van-col span="24">
        <van-cell-group>
          <van-cell title="本人登记使用的车辆" style="font-weight: bold" />
          <van-cell title="无数据" v-if="userRecordMyList.length === 0" />
          <!-- 登记使用车辆列表 -->
          <van-cell v-for="(item, i) in userRecordMyList" :key="i">
            <!-- 使用 right-icon 插槽来自定义右侧图标 -->
            <template #icon>
              <div>
                <van-image
                  style="width: 100px; height: 70px; max-width: 100%"
                  :src="item.img"
                />
                <!-- <img style="width:100px;height:70px" src="../../assets/images/car_1.jpeg" /> -->
              </div>
            </template>
            <template #right-icon>
              <van-button
                type="primary"
                size="small"
                style="margin-top: 10px"
                v-if="item.status === 2"
                @click="toFlow(1, item)"
                >开始用车</van-button
              >
              <van-button
                type="info"
                size="small"
                style="margin-top: 10px"
                v-if="item.status === 3"
                @click="toFlow(3, item)"
                >归还车辆</van-button
              >
              <van-button
                type="warning"
                size="small"
                style="margin-top: 10px"
                v-if="item.status === 1 || item.status === 4"
                @click="toFlow(2, item)"
                >取消申用</van-button
              >
            </template>
            <template #title>
              <div style="margin-left: 5px">
                <div style="font-size: 16px">
                  <van-tag
                    v-if="item.vehicleInfo.vehicleType === 1"
                    type="primary"
                    >试</van-tag
                  >
                  <van-tag
                    v-else-if="item.vehicleInfo.vehicleType === 2"
                    type="primary"
                    >客</van-tag
                  >
                  <van-tag
                    v-else-if="item.vehicleInfo.vehicleType === 3"
                    type="primary"
                    >救</van-tag
                  >
                  {{ item.vehicleInfo.plateNum }}
                  <van-tag plain type="primary" style="margin-left: 5px">{{
                    item.vehicleInfo.isActive
                  }}</van-tag>
                </div>
                <div style="font-size: 14px; color: #949494">
                  {{ item.vehicleInfo.vehicleSeries.seriesFactory }} -
                  {{ item.vehicleInfo.vehicleSeries.seriesName }}
                </div>
                <div>
                  {{ currentUser.name }}
                  <van-tag
                    v-if="item.status === 1"
                    plain
                    type="primary"
                    style="margin-left: 5px"
                    >发起中</van-tag
                  >
                  <van-tag
                    v-if="item.status === 2"
                    plain
                    type="primary"
                    style="margin-left: 5px"
                    >审批通过</van-tag
                  >
                  <van-tag
                    v-if="item.status === 3"
                    plain
                    type="primary"
                    style="margin-left: 5px"
                    >用车中</van-tag
                  >
                  <van-tag
                    v-if="item.status === 4"
                    plain
                    type="primary"
                    style="margin-left: 5px"
                    >审批拒绝</van-tag
                  >
                </div>
              </div>
            </template>
          </van-cell>
        </van-cell-group>

        <van-cell-group>
          <van-cell title="公司其他在用车辆" style="font-weight: bold" />
          <van-cell title="无数据" v-if="userRecordOtherList.length === 0" />
          <!-- 登记使用车辆列表 -->
          <van-cell v-for="(item, i) in userRecordOtherList" :key="i">
            <!-- 使用 right-icon 插槽来自定义右侧图标 -->
            <template #icon>
              <div>
                <van-image
                  style="width: 100px; height: 70px; max-width: 100%"
                  :src="item.img"
                />
                <!-- <img style="width:100px;height:70px" src="../../assets/images/car_1.jpeg" /> -->
              </div>
            </template>
            <template #right-icon>
              <!-- <van-button type="primary" size="small" style="margin-top: 10px"
                >归还车辆</van-button
              > -->
            </template>
            <template #title>
              <div style="margin-left: 5px">
                <div style="font-size: 16px">
                  <van-tag
                    v-if="item.vehicleInfo.vehicleType === 1"
                    type="primary"
                    >试</van-tag
                  >
                  <van-tag
                    v-else-if="item.vehicleInfo.vehicleType === 2"
                    type="primary"
                    >客</van-tag
                  >
                  <van-tag
                    v-else-if="item.vehicleInfo.vehicleType === 3"
                    type="primary"
                    >救</van-tag
                  >
                  {{ item.vehicleInfo.plateNum }}
                  <van-tag plain type="primary" style="margin-left: 5px">{{
                    item.vehicleInfo.isActive
                  }}</van-tag>
                </div>
                <div style="font-size: 14px; color: #949494">
                  {{ item.vehicleInfo.vehicleSeries.seriesFactory }} -
                  {{ item.vehicleInfo.vehicleSeries.seriesFactory.seriesName }}
                </div>
                <div>
                  {{ item.driverName }}
                  <van-tag
                    v-if="item.status === 1"
                    plain
                    type="primary"
                    style="margin-left: 5px"
                    >发起中</van-tag
                  >
                  <van-tag
                    v-if="item.status === 2"
                    plain
                    type="primary"
                    style="margin-left: 5px"
                    >审批通过</van-tag
                  >
                  <van-tag
                    v-if="item.status === 3"
                    plain
                    type="primary"
                    style="margin-left: 5px"
                    >用车中</van-tag
                  >
                  <van-tag
                    v-if="item.status === 4"
                    plain
                    type="primary"
                    style="margin-left: 5px"
                    >审批拒绝</van-tag
                  >
                  <van-tag
                    v-if="item.status === 5"
                    plain
                    type="primary"
                    style="margin-left: 5px"
                    >还车成功</van-tag
                  >
                  <van-tag
                    v-if="item.status === 6"
                    plain
                    type="primary"
                    style="margin-left: 5px"
                    >流程结束</van-tag
                  >
                  <van-tag
                    v-if="item.status === 6"
                    plain
                    type="primary"
                    style="margin-left: 5px"
                    >取消用车</van-tag
                  >
                </div>
              </div>
            </template>
          </van-cell>
        </van-cell-group>

        <van-cell-group>
          <van-cell title="公司未用车辆" style="font-weight: bold" />
          <van-cell title="无数据" v-if="vehicleNonUsingList.length === 0" />
          <van-cell v-for="(item, i) in vehicleNonUsingList" :key="i">
            <!-- 使用 right-icon 插槽来自定义右侧图标 -->
            <template #icon>
              <div>
                <van-image
                  style="width: 100px; height: 70px; max-width: 100%"
                  :src="item.img"
                />
              </div>
            </template>
            <template #right-icon>
              <van-button
                type="primary"
                size="small"
                style="margin-top: 10px"
                @click="regUserRecord(item)"
                >登记使用</van-button
              >
            </template>
            <template #title>
              <div style="margin-left: 5px">
                <div style="font-size: 16px">
                  <van-tag v-if="item.vehicleType === 1" type="primary"
                    >试</van-tag
                  >
                  <van-tag v-else-if="item.vehicleType === 2" type="primary"
                    >客</van-tag
                  >
                  <van-tag v-else-if="item.vehicleType === 3" type="primary"
                    >救</van-tag
                  >
                  {{ item.plateNum }}
                  <van-tag plain type="primary">{{ item.isActive }}</van-tag>
                </div>
                <div style="font-size: 14px; color: #949494">
                  {{ item.vehicleSeries.seriesFactory }} -
                  {{ item.vehicleSeries.seriesFactory.seriesName }}
                </div>
                <div>无人使用</div>
              </div>
            </template>
          </van-cell>
        </van-cell-group>
      </van-col>
    </van-row>
    

    <van-row>
      <van-col span="24">
        <van-cell
          style="height: 40px; background-color: white"
          class="bg_grey"
        ></van-cell>
      </van-col>
    </van-row>
    </van-pull-refresh>
  </div>
</template>

<script>
import { Api, base_uri } from "../../api/api_config";
import { Toast } from "vant";

export default {
  data() {
    return {
      baseUri: '',
      currentUser: {},
      vehicleList: [],
      userRecordList: [],
      userRecordMyList: [],
      userRecordOtherList: [],
      vehicleNonUsingList: [],
      snArr: [],
      snList: [],
      isLoading: false,
      company_logo: '',
      company_address: ''
    };
  },
  created() {
    this.initData();
  },
  mounted() {},
  methods: {
    initData() {
      this.baseUri = base_uri;
      this.$store.state.tab_show = true;

      // 获取company对象
      this.currentUser = this.$store.state.configuration.currentUser;

      // 获取vehicle
      // 清空数据
      this.clear();
      this.getLogo();
      this.queryVehicle();
    },
    getLogo() {
      let that = this;
      this.$axios({
        method: Api.Company.company.method,
        url:
          Api.Company.company.url + "?id=" + this.currentUser.depId,
      })
        .then(function (res) {
          res.data.items.forEach(element => {
            if (element.id === that.currentUser.depId) {
              if (element.attachmentList.length > 0) {
                that.company_logo = that.baseUri + element.attachmentList[0].file_path
              }
              that.company_address = element.province + ' ' + element.city + ' ' + element.reMark
            }
          });
        })
        .catch(function (e) {
          console.log(e)
        });
    },
    redirectSubPage(e) {
      this.$store.state.tab_show = false;
      this.$router.push("/carUsage/" + e);
    },
    queryVehicle() {
      let that = this;
      this.isLoading = false;
      Toast.loading({
        message: "加载中...",
        forbidClick: true,
      });
      this.$axios({
        method: Api.Vehicle.get_vehicle.method,
        url:
          Api.Vehicle.get_vehicle.url + "?CompanyId=" + this.currentUser.depId,
      })
        .then(function (res) {
          that.vehicleList = res.data.items;
          console.log(that.vehicleList)
          that.queryUserRecord();
        })
        .catch(function (e) {
          console.log(e)
          Toast.clear()
        });
    },
    queryUserRecord() {
      let that = this;
      this.$axios({
        method: Api.useRecord.useRecord.method,
        url:
          Api.useRecord.useRecord.url +
          "?CompanyId=" +
          this.currentUser.depId +
          "&isUsing=true",
      })
        .then(function (res) {
          that.userRecordList = res.data.items;

          // 处理数据
          that.oprateData();
        })
        .catch(function (e) {
          console.log(e)
          Toast.clear()
        });
    },
    oprateData() {
      let that = this;
      // 先循环userRecord,筛选出个人数据
      that.userRecordList.forEach((element) => {
        that.vehicleList.forEach(ele => {
          if (ele.id ===  element.vehicleInfo.id) {
            element.vehicleInfo.vehicleAttachmentList = ele.vehicleAttachmentList
          }
        })
        // 赋予属性
        element.vehicleInfo.isActive = "读取中";
        // 判断是否属于用户个人记录
        if (element.vehicleInfo.vehicleAttachmentList !== null) {
          if (element.vehicleInfo.vehicleAttachmentList.length > 0) {
            element.img = that.baseUri + element.vehicleInfo.vehicleAttachmentList[0].file_path
          } else {
            element.img = ''
          }
        } else {
          element.img = ''
        }
        if (element.creatorId === this.currentUser.id) {
          that.userRecordMyList.push(element);
        } else {
          that.userRecordOtherList.push(element);
        }

        // 筛选除了userRecord记录以外的Vehicle记录
        // this.vehicleList.forEach((ele) => {
        //   if (element.vehicleInfo.id === ele.id) {
        //     ele.isUsing = true;
        //   } else {
        //     ele.isUsing = false;
        //   }
        // });

        // 添加到snArr
        that.snArr.push(element.vehicleInfo.sn);
      });
      
      
      this.vehicleList.forEach((ele) => {
        if (ele.runStatus === 1) {
          let isContains = false;
          that.userRecordList.forEach((e) => {
            if (e.vehicleInfo.id === ele.id) {
              isContains = true
            }
          });
          if (isContains === false) {
            ele.isActive = "读取中";
            if (ele.vehicleAttachmentList !== null) {
              if (ele.vehicleAttachmentList.length > 0) {
                ele.img = that.baseUri + ele.vehicleAttachmentList[0].file_path
              } else {
                ele.img = ''
              }
            } else {
              ele.img = ''
            }

            that.vehicleNonUsingList.push(ele);
            that.snArr.push(ele.sn);
          }
        }
      });

      // console.log(this.userRecordMyList);
      // console.log(this.userRecordOtherList);
      // console.log(this.vehicleNonUsingList);

      // for (let index = 0; index < this.vehicleNonUsingList.length; index++) {
      //   const element = this.vehicleNonUsingList[index];
      //   console.log(element.sn)
      // }

      Toast.clear();
      this.querySN();
    },
    querySN() {
      // 拼接SN
      let addUrl = "";
      for (let i = 0; i < this.snArr.length; i++) {
        const element = this.snArr[i];
        if (i === 0) {
          addUrl += "?sns=" + element;
        } else {
          addUrl += "&sns=" + element;
        }
      }

      let that = this;
      this.$axios({
        method: Api.position.position.method,
        url: Api.position.position.url + addUrl,
      })
        .then(function (res) {
          that.snList = res.data.items;
          // 处理数据
          that.oprateDataSN();
        })
        .catch(function (e) {
          console.log(e);
        });
    },
    oprateDataSN() {
      let that = this;
      this.userRecordMyList.forEach((element) => {
        that.snList.forEach((ele) => {
          if (element.vehicleInfo.sn === ele.sn) {
            let temp_time = that.$moment(ele.time);
            let sys_time = that.$moment(ele.sys_time);
            // 增加30分钟，若大于系统现在时间，则其在线，否则离线
            temp_time.add(30, "m");
            if (temp_time.isSameOrBefore(sys_time)) {
              // 离线，设备时间增加30分钟，还在系统时间之前
              element.vehicleInfo.isActive = "离线";
            } else {
              // 在线
              element.vehicleInfo.isActive = "在线";
            }
          }
        });
      });

      this.userRecordOtherList.forEach((element) => {
        that.snList.forEach((ele) => {
          if (element.vehicleInfo.sn === ele.sn) {
            // let temp_time = that.$moment(ele.time);
            // let sys_time = that.$moment(ele.sys_time);
            // // 增加30分钟，若大于系统现在时间，则其在线，否则离线
            // temp_time.add(30, "m");
            // if (temp_time.isSameOrBefore(sys_time)) {
            //   // 离线，设备时间增加30分钟，还在系统时间之前
            //   element.vehicleInfo.isActive = "离线";
            // } else {
            //   // 在线
            //   element.vehicleInfo.isActive = "在线";
            // }
            if (ele.online_status === 1) {
              element.vehicleInfo.isActive = "在线";
            } else {
              element.vehicleInfo.isActive = "离线";
            }
          }
        });
      });

      this.vehicleNonUsingList.forEach((element) => {
        that.snList.forEach((ele) => {
          if (element.sn === ele.sn) {
            // let temp_time = that.$moment(ele.time);
            // let sys_time = that.$moment(ele.sys_time);
            // // 增加30分钟，若大于系统现在时间，则其在线，否则离线
            // temp_time.add(30, "m");
            // if (temp_time.isSameOrBefore(sys_time)) {
            //   // 离线，设备时间增加30分钟，还在系统时间之前
            //   element.isActive = "离线";
            // } else {
            //   // 在线
            //   element.isActive = "在线";
            // }
            if (ele.online_status === 1) {
              element.isActive = "在线";
            } else {
              element.isActive = "离线";
            }
          }
        });
      });

      // 强制刷新一次页面
      
      this.$forceUpdate();

    },
    regUserRecord(item) {
      this.$store.state.vehicle = item;
      this.$router.push("/carUsage/regCar");
    },
    toFlow(flow, item) {
      this.$store.state.record_flow = flow;
      this.$store.state.useRecord = item;
      this.$router.push("/carUsage/flowCar")
    },
    clear() {
      this.vehicleList = [];
      this.userRecordList = [];
      this.userRecordMyList = [];
      this.userRecordOtherList = [];
      this.vehicleNonUsingList = [];
      this.snArr = [];
      this.snList = [];
    },
    onRefresh() {
      this.initData();
    }
  },
};
</script>

<style scoped>
.cell .van-cell__title {
  min-width: 80%;
}
.item_font {
  font-size: 14px;
  color: #576b95;
  font-weight: bold;
}
</style>
